/**
 * UI 管理器
 * 处理用户界面交互和显示
 */

class UI {
  constructor() {
    this.elements = {};
    this.currentUser = null;
    this.onlineUsers = [];
    this.messageHistory = [];
    this.settings = this.loadSettings();
    
    this.init();
  }
  
  /**
   * 初始化 UI
   */
  init() {
    this.bindElements();
    this.bindEvents();
    this.applySettings();
  }
  
  /**
   * 绑定 DOM 元素
   */
  bindElements() {
    this.elements = {
      // 主要容器
      loading: Utils.dom.$('#loading'),
      app: Utils.dom.$('#app'),
      
      // 头部元素
      connectionStatus: Utils.dom.$('#connectionStatus'),
      onlineCounter: Utils.dom.$('#onlineCounter'),
      settingsBtn: Utils.dom.$('#settingsBtn'),
      
      // 聊天区域
      chatMessages: Utils.dom.$('#chatMessages'),
      messageInput: Utils.dom.$('#messageInput'),
      sendBtn: Utils.dom.$('#sendBtn'),
      charCounter: Utils.dom.$('#charCounter'),
      
      // 用户列表
      userList: Utils.dom.$('#userList'),
      sidebar: Utils.dom.$('#sidebar'),
      sidebarToggle: Utils.dom.$('#sidebarToggle'),
      
      // 模态框
      userModal: Utils.dom.$('#userModal'),
      userForm: Utils.dom.$('#userForm'),
      nickname: Utils.dom.$('#nickname'),
      joinBtn: Utils.dom.$('#joinBtn'),
      
      // 设置模态框
      settingsModal: Utils.dom.$('#settingsModal'),
      
      // 通知容器
      notifications: Utils.dom.$('#notifications')
    };
  }
  
  /**
   * 绑定事件
   */
  bindEvents() {
    // 用户表单提交
    this.elements.userForm?.addEventListener('submit', (e) => {
      e.preventDefault();
      this.handleJoinChat();
    });
    
    // 消息发送
    this.elements.sendBtn?.addEventListener('click', () => {
      this.handleSendMessage();
    });
    
    // 消息输入框事件
    this.elements.messageInput?.addEventListener('keypress', (e) => {
      if (e.key === 'Enter' && this.settings.enterToSend) {
        this.handleSendMessage();
      }
    });
    
    this.elements.messageInput?.addEventListener('input', () => {
      this.updateCharCounter();
      this.toggleSendButton();
    });
    
    // 设置按钮
    this.elements.settingsBtn?.addEventListener('click', () => {
      this.toggleModal('settingsModal');
    });
    
    // 侧边栏切换
    this.elements.sidebarToggle?.addEventListener('click', () => {
      this.toggleSidebar();
    });
    
    // 模态框关闭
    Utils.dom.$$('.modal-close').forEach(btn => {
      btn.addEventListener('click', (e) => {
        const modal = e.target.closest('.modal-overlay');
        if (modal) {
          this.hideModal(modal.id);
        }
      });
    });
    
    // 点击模态框外部关闭
    Utils.dom.$$('.modal-overlay').forEach(modal => {
      modal.addEventListener('click', (e) => {
        if (e.target === modal) {
          this.hideModal(modal.id);
        }
      });
    });
  }
  
  /**
   * 显示应用程序
   */
  showApp() {
    this.elements.loading.style.display = 'none';
    this.elements.app.style.display = 'flex';
  }
  
  /**
   * 显示用户加入模态框
   */
  showJoinModal() {
    this.showModal('userModal');
    this.elements.nickname?.focus();
  }
  
  /**
   * 处理加入聊天
   */
  handleJoinChat() {
    const nickname = this.elements.nickname?.value.trim();
    
    if (!nickname) {
      this.showNotification('请输入昵称', 'error');
      return;
    }
    
    const validation = Utils.validateNickname(nickname);
    if (!validation.valid) {
      this.showNotification(validation.error, 'error');
      return;
    }
    
    // 触发加入事件
    const event = new CustomEvent('joinChat', {
      detail: { nickname }
    });
    document.dispatchEvent(event);
  }
  
  /**
   * 处理发送消息
   */
  handleSendMessage() {
    const message = this.elements.messageInput?.value.trim();
    
    if (!message) return;
    
    // 触发发送消息事件
    const event = new CustomEvent('sendMessage', {
      detail: { message }
    });
    document.dispatchEvent(event);
    
    // 清空输入框
    this.elements.messageInput.value = '';
    this.updateCharCounter();
    this.toggleSendButton();
  }
  
  /**
   * 更新连接状态
   */
  updateConnectionStatus(status) {
    const indicator = this.elements.connectionStatus?.querySelector('.status-indicator');
    const text = this.elements.connectionStatus?.querySelector('.status-text');
    
    if (indicator) {
      indicator.className = `status-indicator ${status}`;
    }
    
    if (text) {
      const statusText = {
        connecting: '连接中...',
        connected: '已连接',
        disconnected: '已断开',
        error: '连接错误'
      };
      text.textContent = statusText[status] || status;
    }
  }
  
  /**
   * 添加消息到聊天区域
   */
  addMessage(message) {
    const messageEl = this.createMessageElement(message);
    this.elements.chatMessages?.appendChild(messageEl);
    
    // 自动滚动到底部
    if (this.settings.autoScroll) {
      this.scrollToBottom();
    }
    
    // 添加到历史记录
    this.messageHistory.push(message);
    
    // 限制历史记录数量
    const maxHistory = CONFIG.ui.messages.maxHistory;
    if (this.messageHistory.length > maxHistory) {
      this.messageHistory = this.messageHistory.slice(-maxHistory);
      
      // 移除旧的 DOM 元素
      const messages = this.elements.chatMessages?.children;
      if (messages && messages.length > maxHistory) {
        this.elements.chatMessages.removeChild(messages[0]);
      }
    }
  }
  
  /**
   * 创建消息元素
   */
  createMessageElement(message) {
    const messageEl = Utils.dom.create('div', { className: 'message' });
    
    // 系统消息特殊处理
    if (message.from === 'system') {
      messageEl.classList.add('system');
      messageEl.innerHTML = `
        <div class="message-content">
          <div class="message-text">${Utils.escapeHtml(message.content.message || message.content)}</div>
        </div>
      `;
      return messageEl;
    }
    
    // 普通消息
    const avatar = Utils.dom.create('div', { className: 'message-avatar' });
    avatar.textContent = '👤'; // 默认头像
    
    const content = Utils.dom.create('div', { className: 'message-content' });
    
    const header = Utils.dom.create('div', { className: 'message-header' });
    const author = Utils.dom.create('span', { className: 'message-author' });
    author.textContent = message.nickname || message.from;
    
    const time = Utils.dom.create('span', { className: 'message-time' });
    time.textContent = Utils.formatTime(message.timestamp);
    
    header.appendChild(author);
    if (this.settings.showTimestamp) {
      header.appendChild(time);
    }
    
    const text = Utils.dom.create('div', { className: 'message-text' });
    text.textContent = message.content;
    
    content.appendChild(header);
    content.appendChild(text);
    
    if (this.settings.showAvatar) {
      messageEl.appendChild(avatar);
    }
    messageEl.appendChild(content);
    
    return messageEl;
  }
  
  /**
   * 更新在线用户列表
   */
  updateOnlineUsers(users) {
    this.onlineUsers = users;
    
    // 更新计数器
    const counter = this.elements.onlineCounter?.querySelector('.counter-text');
    if (counter) {
      counter.textContent = `${users.length} 人在线`;
    }
    
    // 更新用户列表
    if (this.elements.userList) {
      this.elements.userList.innerHTML = '';
      
      if (users.length === 0) {
        const empty = Utils.dom.create('div', { className: 'user-list-empty' });
        empty.innerHTML = '<p>暂无在线用户</p>';
        this.elements.userList.appendChild(empty);
      } else {
        users.forEach(user => {
          const userEl = this.createUserElement(user);
          this.elements.userList.appendChild(userEl);
        });
      }
    }
  }
  
  /**
   * 创建用户元素
   */
  createUserElement(user) {
    const userEl = Utils.dom.create('div', { className: 'user-item' });
    
    const avatar = Utils.dom.create('div', { className: 'user-avatar' });
    avatar.textContent = '👤';
    
    const info = Utils.dom.create('div', { className: 'user-info' });
    const name = Utils.dom.create('div', { className: 'user-name' });
    name.textContent = user.nickname;
    
    info.appendChild(name);
    userEl.appendChild(avatar);
    userEl.appendChild(info);
    
    return userEl;
  }
  
  /**
   * 显示通知
   */
  showNotification(message, type = 'info', duration = 5000) {
    const notification = Utils.dom.create('div', { 
      className: `notification notification-${type}` 
    });
    
    notification.innerHTML = `
      <span class="notification-message">${Utils.escapeHtml(message)}</span>
      <button class="notification-close">&times;</button>
    `;
    
    // 关闭按钮事件
    const closeBtn = notification.querySelector('.notification-close');
    closeBtn.addEventListener('click', () => {
      this.hideNotification(notification);
    });
    
    // 添加到容器
    this.elements.notifications?.appendChild(notification);
    
    // 自动隐藏
    setTimeout(() => {
      this.hideNotification(notification);
    }, duration);
    
    // 播放声音通知
    if (type === 'message' && this.settings.soundNotification) {
      Utils.audio.playNotification();
    }
  }
  
  /**
   * 隐藏通知
   */
  hideNotification(notification) {
    if (notification && notification.parentNode) {
      notification.parentNode.removeChild(notification);
    }
  }
  
  /**
   * 更新字符计数器
   */
  updateCharCounter() {
    const input = this.elements.messageInput;
    const counter = this.elements.charCounter;
    
    if (input && counter) {
      const length = input.value.length;
      const maxLength = CONFIG.ui.messages.messageMaxLength;
      counter.textContent = `${length}/${maxLength}`;
      
      if (length > maxLength * 0.8) {
        counter.style.color = 'var(--warning-color)';
      } else {
        counter.style.color = 'var(--text-muted)';
      }
    }
  }
  
  /**
   * 切换发送按钮状态
   */
  toggleSendButton() {
    const input = this.elements.messageInput;
    const button = this.elements.sendBtn;
    
    if (input && button) {
      const hasText = input.value.trim().length > 0;
      button.disabled = !hasText || !this.currentUser;
    }
  }
  
  /**
   * 滚动到底部
   */
  scrollToBottom() {
    if (this.elements.chatMessages) {
      Utils.dom.scrollToBottom(this.elements.chatMessages);
    }
  }
  
  /**
   * 显示/隐藏模态框
   */
  showModal(modalId) {
    const modal = Utils.dom.$(`#${modalId}`);
    if (modal) {
      modal.classList.add('active');
    }
  }
  
  hideModal(modalId) {
    const modal = Utils.dom.$(`#${modalId}`);
    if (modal) {
      modal.classList.remove('active');
    }
  }
  
  toggleModal(modalId) {
    const modal = Utils.dom.$(`#${modalId}`);
    if (modal) {
      modal.classList.toggle('active');
    }
  }
  
  /**
   * 切换侧边栏
   */
  toggleSidebar() {
    if (this.elements.sidebar) {
      this.elements.sidebar.classList.toggle('open');
    }
  }
  
  /**
   * 加载设置
   */
  loadSettings() {
    return Utils.storage.get(CONFIG.storage.userPreferences, {
      showTimestamp: true,
      showAvatar: true,
      soundNotification: true,
      autoScroll: true,
      enterToSend: true,
      darkMode: false
    });
  }
  
  /**
   * 保存设置
   */
  saveSettings() {
    Utils.storage.set(CONFIG.storage.userPreferences, this.settings);
  }
  
  /**
   * 应用设置
   */
  applySettings() {
    // 应用暗黑模式
    if (this.settings.darkMode) {
      document.documentElement.setAttribute('data-theme', 'dark');
    } else {
      document.documentElement.removeAttribute('data-theme');
    }
  }
  
  /**
   * 设置当前用户
   */
  setCurrentUser(user) {
    this.currentUser = user;
    this.toggleSendButton();
    
    // 启用消息输入
    if (this.elements.messageInput) {
      this.elements.messageInput.disabled = false;
      this.elements.messageInput.placeholder = '输入消息...';
    }
  }
  
  /**
   * 清除当前用户
   */
  clearCurrentUser() {
    this.currentUser = null;
    this.toggleSendButton();
    
    // 禁用消息输入
    if (this.elements.messageInput) {
      this.elements.messageInput.disabled = true;
      this.elements.messageInput.placeholder = '请先加入聊天室...';
    }
  }
}